<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useEditorStore } from '../stores/editor'
import Konva from 'konva'

const props = defineProps<{
  width: number
  height: number
}>()

const editorStore = useEditorStore()
const canvasContainer = ref<HTMLDivElement>()
let stage: Konva.Stage | null = null
let layer: Konva.Layer | null = null
let transformer: Konva.Transformer | null = null

// 初始化Konva舞台
function initStage() {
  if (!canvasContainer.value) return

  // 创建舞台
  stage = new Konva.Stage({
    container: canvasContainer.value,
    width: props.width,
    height: props.height,
  })

  // 创建图层
  layer = new Konva.Layer()
  stage.add(layer)

  // 创建变换器
  transformer = new Konva.Transformer({
    rotateAnchorOffset: 60,
    enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
  })
  layer.add(transformer)

  // 点击空白区域取消选择
  stage.on('click tap', (e) => {
    if (e.target === stage) {
      transformer!.nodes([])
      editorStore.selectImage(null)
    }
  })

  // 监听拖拽结束事件
  stage.on('dragend', (e) => {
    const node = e.target
    if (node.name() === 'image') {
      const imageId = node.id()
      editorStore.updateImage(imageId, {
        x: node.x(),
        y: node.y()
      })
    }
  })

  // 监听变换结束事件
  stage.on('transformend', (e) => {
    const node = e.target
    if (node.name() === 'image') {
      const imageId = node.id()
      editorStore.updateImage(imageId, {
        x: node.x(),
        y: node.y(),
        scaleX: node.scaleX(),
        scaleY: node.scaleY(),
        rotation: node.rotation()
      })
    }
  })
}

// 添加图片到画布
function addImageToCanvas(imageData: any) {
  if (!layer) return

  const imageObj = new Image()
  imageObj.onload = () => {
    const konvaImage = new Konva.Image({
      id: imageData.id,
      name: 'image',
      image: imageObj,
      x: imageData.x,
      y: imageData.y,
      width: imageData.width,
      height: imageData.height,
      scaleX: imageData.scaleX,
      scaleY: imageData.scaleY,
      rotation: imageData.rotation,
      draggable: true,
    })

    // 点击图片选中
    konvaImage.on('click tap', () => {
      editorStore.selectImage(imageData.id)
      transformer!.nodes([konvaImage])
    })

    layer!.add(konvaImage)
    layer!.batchDraw()
  }
  imageObj.src = imageData.src
}

// 更新图片属性
function updateImageOnCanvas(imageData: any) {
  if (!layer) return

  const imageNode = layer.findOne(`#${imageData.id}`)
  if (imageNode) {
    imageNode.setAttrs({
      x: imageData.x,
      y: imageData.y,
      width: imageData.width,
      height: imageData.height,
      scaleX: imageData.scaleX,
      scaleY: imageData.scaleY,
      rotation: imageData.rotation
    })
    layer.batchDraw()
  }
}

// 从画布移除图片
function removeImageFromCanvas(imageId: string) {
  if (!layer) return

  const imageNode = layer.findOne(`#${imageId}`)
  if (imageNode) {
    imageNode.destroy()
    transformer!.nodes([])
    layer.batchDraw()
  }
}

// 选择图片
function selectImageOnCanvas(imageId: string | null) {
  if (!layer || !transformer) return

  if (imageId) {
    const imageNode = layer.findOne(`#${imageId}`)
    if (imageNode) {
      transformer.nodes([imageNode])
    }
  } else {
    transformer.nodes([])
  }
}

// 清空画布
function clearCanvas() {
  if (!layer) return

  layer.destroyChildren()
  transformer = new Konva.Transformer({
    rotateAnchorOffset: 60,
    enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
  })
  layer.add(transformer)
  layer.batchDraw()
}

// 导出画布为图片
function exportCanvas() {
  if (!stage) return null

  // 临时隐藏变换器
  const transformerVisible = transformer!.visible()
  transformer!.visible(false)
  
  const dataURL = stage.toDataURL({
    mimeType: 'image/png',
    quality: 1,
    pixelRatio: 2
  })
  
  // 恢复变换器显示状态
  transformer!.visible(transformerVisible)
  
  return dataURL
}

// 监听store变化
watch(() => editorStore.images, (newImages, oldImages) => {
  if (!layer) return

  // 处理新增的图片
  newImages.forEach(image => {
    const exists = oldImages?.find(old => old.id === image.id)
    if (!exists) {
      addImageToCanvas(image)
    }
  })

  // 处理删除的图片
  oldImages?.forEach(oldImage => {
    const exists = newImages.find(img => img.id === oldImage.id)
    if (!exists) {
      removeImageFromCanvas(oldImage.id)
    }
  })
}, { deep: true })

// 监听选中图片变化
watch(() => editorStore.selectedImageId, (newId) => {
  selectImageOnCanvas(newId)
})

// 监听画布尺寸变化
watch(() => [props.width, props.height], ([newWidth, newHeight]) => {
  if (stage) {
    stage.width(newWidth)
    stage.height(newHeight)
  }
})

// 监听画布设置变化
watch(() => editorStore.canvasSettings, (newSettings) => {
  if (canvasContainer.value) {
    canvasContainer.value.style.backgroundColor = newSettings.backgroundColor
  }
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initStage()
    
    // 初始化现有图片
    editorStore.images.forEach(image => {
      addImageToCanvas(image)
    })
  })
})

// 暴露方法给父组件
defineExpose({
  exportCanvas,
  clearCanvas
})
</script>

<template>
  <div class="konva-canvas-wrapper">
    <div 
      ref="canvasContainer" 
      class="konva-canvas"
      :style="{
        width: width + 'px',
        height: height + 'px',
        backgroundColor: editorStore.canvasSettings.backgroundColor,
        borderRadius: editorStore.canvasSettings.borderRadius + 'px',
        border: editorStore.canvasSettings.borderWidth > 0 
          ? `${editorStore.canvasSettings.borderWidth}px solid ${editorStore.canvasSettings.borderColor}`
          : 'none'
      }"
    />
  </div>
</template>

<style scoped>
.konva-canvas-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
}

.konva-canvas {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}
</style>
